<?php

/*
 * Plugin Name: wp-xmlrpc-server
 * Description: Extends WordPress web services
 * Version: 1.0
 * Author: Prasath Nadarajah
*/

add_filter( 'xmlrpc_methods', 'newMethods' );

function newMethods( $methods ) {
  $methods['wp.newUser']       = 'wp_newUser';
  return $methods;
}

function wp_newUser( $args ) {

            global $wp_xmlrpc_server;


            $wp_xmlrpc_server->escape($args);

            $blog_ID     = (int) $args[0]; // for future use
            $username  = $args[1];
            $password   = $args[2];
            $content_struct = $args[3];
            $send_mail     = isset( $args[4] ) ? $args[4] : false; // default value can be anything

            if ( !$wp_xmlrpc_server->login( $username, $password )  )
                return new IXR_Error( 401, $wp_xmlrpc_server->error->message );

            if ( !current_user_can( 'create_users' ) )
                return new IXR_Error( 403, __( 'You are not allowed to create users' ) );


            // check whether email address is valid
            if(!is_email($content_struct['email']))
                return new IXR_Error( 403, __( 'email id is not valid' ) );

            //password cannot be empty
            if(empty ($content_struct['password']))
                return new IXR_Error( 403, __( 'password cannot be empty' ) );

            $user_data = array(
                    'user_login'        => $content_struct['username'],
                    'user_email'        => $content_struct['email'],
                    'first_name'        => $content_struct['firstname'],
                    'last_name'         => $content_struct['lastname'],
                    'user_url'          => $content_struct['website'],
                    'user_pass'         => $content_struct['password'],
                    'role'              => $content_struct['role'],
            );


            $user_id =  wp_insert_user($user_data);

            if ( is_wp_error( $user_id ) )
			return new IXR_Error(500, $user_id->get_error_message());

            if ( !$user_id )
			return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));

            // send an email to the user
            if($send_mail) {
                // this is a simple email
                // this can be improved
                mail($content_struct['email'], "subject", "message");
            }

            return strval($user_id);


}

?>
